package cn.iocoder.yudao.module.member.level.api;

import cn.iocoder.yudao.module.api.member.level.MemberLevelApi;
import cn.iocoder.yudao.module.api.member.level.dto.MemberLevelRespDTO;
import cn.iocoder.yudao.module.api.member.user.enums.MemberExperienceBizTypeEnum;
import cn.iocoder.yudao.module.member.level.convert.MemberLevelConvert;
import cn.iocoder.yudao.module.member.level.service.MemberLevelService;
import cn.iocoder.yudao.module.member.user.dal.dataobject.MemberUserDO;
import cn.iocoder.yudao.module.member.user.service.MemberUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.api.member.ErrorCodeConstants.EXPERIENCE_BIZ_NOT_SUPPORT;

/**
 * 用户等级 API 实现类
 *
 * @author owen
 */
@Service
@Validated
public class MemberLevelApiImpl implements MemberLevelApi {

    @Resource
    private MemberLevelService memberLevelService;
    @Resource
    private MemberUserService memberUserService;

    @Override
    public MemberLevelRespDTO getMemberLevelByUserId(Long userId) {
        MemberUserDO user = memberUserService.getUser(userId);
        if (user == null || user.getLevelId() == null || user.getLevelId() <= 0) {
            return null;
        }
        return MemberLevelConvert.INSTANCE.convert02(memberLevelService.getLevel(user.getLevelId()));
    }

    @Override
    public int getMemberLevelDiscountPercentByUserId(Long userId) {
        return memberLevelService.getMemberLevelDiscountPercentByUserId(userId);
    }

    @Override
    public void addExperience(Long userId, Integer experience, Integer bizType, String bizId) {
        MemberExperienceBizTypeEnum bizTypeEnum = MemberExperienceBizTypeEnum.getByType(bizType);
        if (bizTypeEnum == null) {
            throw exception(EXPERIENCE_BIZ_NOT_SUPPORT);
        }
        memberLevelService.addExperience(userId, experience, bizTypeEnum, bizId);
    }

    @Override
    public void reduceExperience(Long userId, Integer experience, Integer bizType, String bizId) {
        addExperience(userId, -1 * experience, bizType, bizId);
    }

}
